package edu.hcnu.controller;

import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;


@RestController
@RequestMapping("/file")
public class FileController {

    @GetMapping("index")
    public ModelAndView index(){
        System.out.println("fileStorageLocation = " + fileStorageLocation);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("index");
        return modelAndView;
    }


    @PostMapping("/upload")
    public ModelAndView upload(@RequestParam("file") MultipartFile file) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("index");

        if (file.isEmpty()) {
            modelAndView.addObject("message", "文件内容为空!");
            return modelAndView;
        }
        String fileName = UUID.randomUUID().toString() + "_" + file.getOriginalFilename();



        File dir = new File(fileStorageLocation);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        File dest = new File(fileStorageLocation + fileName);
        try {
            file.transferTo(dest);
            modelAndView.addObject("message", "上传成功!");

        } catch (IOException e) {
            e.printStackTrace();
            modelAndView.addObject("message", "上传失败!");
        }
        return modelAndView;
    }

    private final String fileStorageLocation = "F:\\uploads\\";

    @GetMapping("/download/{fileName:.+}")
    public ResponseEntity<Resource> downloadFile(@PathVariable String fileName) {
        Path path = Paths.get(fileStorageLocation).resolve(fileName);
        Resource resource = null;
        try {
            resource = new UrlResource(path.toUri());
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        return ResponseEntity.ok()
                .contentType(MediaType.parseMediaType(MediaType.APPLICATION_OCTET_STREAM_VALUE))
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; fileName=\"" + resource.getFilename() + "\"")
                .body(resource);
    }

    @GetMapping("download/index")
    public  ModelAndView downloadIndex(){
        File folder = new File(fileStorageLocation);
        File[] listOfFiles = folder.listFiles();
        List<String> filenames=new ArrayList<>();
        for (File file : listOfFiles) {
            if (file.isFile()) {
                System.out.println(file.getName());
            filenames.add(file.getName());
            }
        }
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("table");
        modelAndView.addObject("filenames",filenames);
        return  modelAndView;
    }

}
